<template>
  <div class="map-box">
    <div class="map" id="map"></div>

    <!-- popup HTML -->
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
import Overlay from "ol/Overlay";
import TileLayer from "ol/layer/Tile";
import TileArcGISRest from "ol/source/TileArcGISRest";
import View from "ol/View";
import XYZ from "ol/source/XYZ";
import { toLonLat } from "ol/proj";
import { toStringHDMS } from "ol/coordinate";

import CONSTANT from "@/config/constant.js";

export default {
  name: "overlay",

  data() {
    return {
      map: null,
      overlay: null
    };
  },

  methods: {
    init() {
      this.map = new Map({
        target: "map",
        layers: [
          new TileLayer({
            source: new TileArcGISRest({
              url: CONSTANT.GIS_URL
            })
          })
        ],
        view: new View({
          center: [113.0567, 23.67537],
          maxZoom: 18,
          minZoom: 8,
          zoom: 13,
          projection: "EPSG:4326"
        })
      });

      this.addPopup();
    },

    //添加弹出层
    addPopup() {
      this.overlay = new Overlay({
        element: document.getElementById("popup"),
        autoPan: true,
        autoPanAnimation: {
          duration: 250
        }
      });
      //添加 overlay 到 map
      this.map.addOverlay(this.overlay);

      // 关闭弹出层
      var closer = document.getElementById("popup-closer");
      closer.onclick = ()=> {
        this.overlay.setPosition(undefined);
        closer.blur();
        return false;
      };
    }
  },

  mounted() {
    this.init();

    //点击地图，弹出弹出层
    this.map.on("singleclick",(evt)=>{
      const coordinate = evt.coordinate;
      const hdms = toStringHDMS(toLonLat(coordinate));
      document.getElementById("popup-content").innerHTML =
        "<p>You clicked here:</p><code>" + hdms + "</code>";
      this.overlay.setPosition(coordinate);
    });
  }
};
</script>

<style lang="less" scoped>
.map-box,
.map {
  height: 100%;
}
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 280px;
}
.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}
.ol-popup-closer:after {
  content: "✖";
}
</style>